package com.bestcem.xm.txtanls.util;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.txtanls.handler.RecordExcelWriteHandler;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liheng
 * @version v1.0
 * @date 2021/5/11-15:02
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class FileUtils {

    public final static String INDUSTRY_KEYWORD_FILE_PATH = "/file/keywordSource.json";
    public final static String FILE_PATH = System.getProperty("user.dir");


    /**
     * 生成原话记录文件流
     *
     * @param list
     * @param path
     * @return
     * @author liheng
     * @date 2021/5/19 14:51
     */
    public static <T> File creatRecordExcel(List<T> list, String path) {
        if (log.isInfoEnabled()) {
            log.info("[Txtanls] FILE_PATH: {}; fileName: {}", FILE_PATH, path);
        }
        File file = new File(path);
        // 使用xlsx格式
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("content", "原话");
        writer.addHeaderAlias("emotionName", "情感倾向");
        writer.addHeaderAlias("fieldName", "所属字段名称");
        writer.addHeaderAlias("recordTime", "原话记录时间");
        writer.write(list, true);
        writer.flush(file);
        writer.close();
        return file;
    }

    /**
     * 生成原话记录文件流通过easyexcel
     *
     * @param list
     * @param fileAllPath
     * @return
     * @author liheng
     * @date 2021/5/19 14:51
     */
    public static <T> File creatRecordEasyExcel(List<T> list, String fileAllPath) {
        if (log.isInfoEnabled()) {
            log.info("[Txtanls] EASY EXCEL FILE_PATH: {}; fileName: {}", FILE_PATH, fileAllPath);
        }
        File file = new File(fileAllPath);
        if (CollUtil.isEmpty(list)) {
            list = new ArrayList<>(10);
        }
        // 设置导出cell格式
        RecordExcelWriteHandler excelWriteHandler = new RecordExcelWriteHandler();
        Map<String, String> headerTypeMap = new HashMap<>();
        headerTypeMap.put("原话", "string");
        headerTypeMap.put("情感倾向", "string");
        headerTypeMap.put("所属字段名称", "string");
        headerTypeMap.put("原话记录时间", "string");
        // 设置映射
        excelWriteHandler.setHeaderTypeMap(headerTypeMap);
        // 使用xlsx格式
        com.alibaba.excel.ExcelWriter build = EasyExcel.write(file)
                .registerWriteHandler(excelWriteHandler)
                .useDefaultStyle(false)
                .head(head())
                .build();
        WriteSheet writeSheet = EasyExcel.writerSheet().sheetName("sheet").build();
        if (CollUtil.isNotEmpty(list)) {
            build.write(list, writeSheet);
        } else {
            list = new ArrayList<>(10);
            build.write(list, writeSheet);
        }
        build.finish();
        return file;
    }

    private static List<List<String>> head() {
        List<List<String>> list = new ArrayList<>();
        List<String> head0 = new ArrayList<>();
        head0.add("原话");
        List<String> head1 = new ArrayList<>();
        head1.add("情感倾向");
        List<String> head2 = new ArrayList<>();
        head2.add("所属字段名称");
        List<String> head3 = new ArrayList<>();
        head3.add("原话记录时间");
        list.add(head0);
        list.add(head1);
        list.add(head2);
        list.add(head3);
        return list;
    }

    /**
     * 读取json文件
     *
     * @param filePath
     * @return
     * @author liheng
     * @date 2021/5/19 14:52
     */
    public static Map<String, JSONArray> readIndustryKeywordFile(String filePath) {
        ClassPathResource classPathResource = new ClassPathResource(filePath, FileUtils.class);
        File file;
        Map<String, JSONArray> keywordMap = new HashMap<>();
        try {
            file = classPathResource.getFile();
        } catch (IOException e) {
            if (log.isErrorEnabled()) {
                log.error("[Txtanls] read IndustryKeyword file error! path:{}", filePath);
            }
            return keywordMap;
        }
        if (!file.isFile()) {
            if (log.isErrorEnabled()) {
                log.error("[Txtanls] read IndustryKeyword file error! path:{}", filePath);
            }
            return keywordMap;
        }

        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            keywordMap = JSONObject.parseObject(fileInputStream, Map.class);
        } catch (IOException e) {
            if (log.isErrorEnabled()) {
                log.error("解析行业关键词json出现异常，异常信息：", e);
            }
            return keywordMap;
        }
        return keywordMap;
    }
}
